<template>
    <div class="w-full bg-[#f3f6f9]">
        <div class="m-auto  py-[2rem]  w-[70rem] bg-[#fff]">
            <div class="px-[2rem]">
                
                <!-- 标题输入 -->
                <div class="flex justify-between items-center pb-[1rem] mb-[1rem]" style="border-bottom: 1px solid #E2E8F0;">
                    <input
                        v-model="formData.title"
                        class="w-full text-[1.25rem] font-bold outline-none border-none bg-transparent focus:border-b-2 focus:border-blue-500 transition-all"
                        placeholder="请输入标题"
                        maxlength="60"
                    />
                    <div class="text-right text-[0.875rem] text-[#64748b] mt-1">
                        {{ formData.title.length }}/60
                    </div>
                </div>
                
                <!-- 描述输入 -->
                <!-- <div class="mb-[2rem]">
                    <el-input
                        v-model="formData.description"
                        class="w-full text-[1rem] outline-none border-none bg-transparent"
                        placeholder="请输入描述，50-100字"
                        maxlength="100"
                        show-word-limit
                    />
                </div> -->
                <!-- 编辑器区域 -->
                <div class="mb-[2rem]">
                    <div v-if="editorMode === 'markdown'">
                        <MdEditor 
                            v-model="formData.content" 
                            placeholder="请输入正文"
                            height="30rem"
                        />
                    </div>
                    <div v-else>
                        <Editor 
                            v-model="formData.content" 
                            placeholder="请输入正文" 
                        />
                    </div>
                </div>

            </div>
            <!-- 底部操作栏 -->
            <div class="flex flex-col justify-between items-start mt-[2rem] gap-[1rem] p-[2rem] pb-[0]" style="border-top: 1px solid #E2E8F0;">
                <div class="flex flex-col gap-[1rem]">
                    <!-- 标签区域 -->
                    <div class="flex items-center gap-[0.5rem]">
                        <span class="text-[0.875rem] font-medium">文章标签:</span>
                        <div class="flex items-center gap-[0.5rem] flex-wrap">
                            <div v-for="(tag, index) in formData.tags" :key="index" 
                                class="flex items-center gap-[0.25rem] h-[2rem] px-[0.75rem] py-[0.25rem] rounded-[999px] bg-gray-100 text-gray-700">
                                <span>{{ tag }}</span>
                                <el-icon class="cursor-pointer hover:text-red-500" @click="handleRemoveTag(index)">
                                    <Close />
                                </el-icon>
                            </div>
                        </div>

                        <!-- 添加标签按钮 -->
                        <div v-if="formData.tags.length < 3" 
                            class="tool-item relative">
                            <button class="topic-trigger flex items-center gap-[0.25rem] h-[2.375rem] px-[1.1rem] py-[0.45rem] rounded-[0.5rem] bg-[#fff] text-[#000] ml-[0.5rem] text-[1rem] cursor-pointer border border-[#000] hover:bg-[#000] hover:text-[#fff] transition-all duration-300" @click="handleTopicClick">
                                <el-icon><Plus /></el-icon> 添加标签
                            </button>
                            <TagDropdown 
                                :visible="showTagDropdown" 
                                @select="onTagSelected" 
                                @close="showTagDropdown = false"
                                top="100%"
                            />
                        </div>
                    </div>

                    <!-- 文章封面 -->
                    <div class="flex items-center gap-[0.5rem]">
                        <span class="text-[0.875rem] font-medium">文章封面:</span>
                        <div v-if="formData.coverImage" class="relative">
                            <img :src="formData.coverImage" alt="封面" class="w-[100px] h-[100px] object-cover rounded-[0.5rem]">
                            <div class="absolute top-[0.25rem] right-[0.25rem] bg-white rounded-full p-[0.25rem] cursor-pointer" @click="removeCoverImage">
                                <el-icon><Close /></el-icon>
                            </div>
                        </div>
                        <el-upload
                            v-else
                            class="cover-uploader"
                            action="#"
                            :auto-upload="false"
                            :show-file-list="false"
                            :on-change="handleCoverUpload"
                            accept="image/*"
                        >
                            <div class="w-[100px] h-[100px] border border-dashed border-gray-300 rounded-[0.5rem] flex items-center justify-center cursor-pointer hover:border-[#2563eb]">
                                <div class="flex flex-col items-center">
                                    <el-icon class="text-[1.5rem]"><Plus /></el-icon>
                                    <span class="text-[0.75rem] mt-[0.5rem]">本地上传</span>
                                </div>
                            </div>
                        </el-upload>
                    </div>

                    <!-- 附件区域 -->
                    <div class="flex items-center gap-[0.5rem]">
                        <span class="text-[0.875rem] font-medium">添加附件:</span>
                        <div v-if="formData.attachments && formData.attachments.length > 0" class="flex flex-col gap-[0.5rem]">
                            <div v-for="(file, index) in formData.attachments" :key="index" class="flex items-center gap-[0.5rem]">
                                <span class="text-[0.875rem]">{{ file.name }}</span>
                                <el-icon class="cursor-pointer hover:text-red-500" @click="removeAttachment(index)"><Close /></el-icon>
                            </div>
                        </div>
                        <el-upload
                            class="attachment-uploader"
                            action="#"
                            :auto-upload="false"
                            :show-file-list="false"
                            :on-change="handleAttachmentUpload"
                        >
                            <div class="flex items-center justify-center h-[2.5rem] px-[1rem] border border-dashed border-gray-300 rounded-[0.5rem] cursor-pointer hover:border-[#2563eb]">
                                <el-icon class="mr-[0.5rem]"><Plus /></el-icon>
                                <span class="text-[0.875rem]">本地上传</span>
                            </div>
                        </el-upload>
                    </div>
                </div>
                
                <div class="flex gap-[1rem] w-full justify-end">
                    <button 
                        type="button"
                        class="h-[2.375rem] px-[1.1rem] py-[0.45rem] rounded-[0.5rem] bg-[#fff] text-[#000] ml-[0.5rem] text-[1rem] cursor-pointer border border-[#000] hover:bg-[#000] hover:text-[#fff] transition-all duration-300"
                        @click="toggleEditorMode"
                    >
                        {{ editorMode === 'markdown' ? '切换富文本编辑器' : '切换Markdown编辑器' }}
                    </button>
                    <button 
                        type="button"
                        class="h-[2.375rem] px-[1.1rem] py-[0.45rem] rounded-[0.5rem] bg-[#fff] text-[#000] ml-[0.5rem] text-[1rem] cursor-pointer border border-[#000] hover:bg-[#000] hover:text-[#fff] transition-all duration-300"
                        @click="togglePreview"
                    >
                        预览
                    </button>
                    <button 
                        type="button"
                        class="h-[2.375rem] px-[1.1rem] py-[0.45rem] rounded-[0.5rem] bg-[#000] text-[#fff] ml-[0.5rem] text-[1rem] cursor-pointer hover:opacity-80 transition-all duration-300"
                        @click="handleSubmit"
                        :disabled="isSubmitting"
                    >
                        {{ isSubmitting ? '发布中...' : '发布' }}
                    </button>
                </div>
            </div>
        </div>

        <!-- 预览弹窗 -->
        <el-dialog
            v-model="showPreview"
            title="预览"
            width="70%"
            :close-on-click-modal="false"
            class="preview-dialog"
        >
            
            <div class="text-[1.25rem] font-bold text-[#000] pt-[1rem]" style="border-top: 1px solid #E2E8F0;">
                {{ formData.title }}
            </div>
            <div class="text-[0.875rem] text-[#567895] mt-[0.5rem]">
                来自:
            </div>
            <div class="flex items-center justify-between gap-[0.5rem]  h-[1.5rem] font-size-[0.875rem] mt-[1rem] mb-[1rem]">
                <!-- 用户头像 -->
                <div class="flex items-center gap-[0.5rem]">
                    <img :src="userStore.avatar" alt="用户头像" class="w-[2rem] h-[2rem] rounded-full"> 
                    <span class="text-[0.875rem] text-[#000]">{{ userStore.nickname }}</span>
                </div>
                
                <!-- 发布时间当前时间 -->
                <div class="text-[0.875rem] text-[#64748b]">
                    {{ new Date().toLocaleString() }}
                </div>
            </div>
            <!-- <div class="text-[0.875rem] text-gray-500 mt-[0.5rem]">
                {{ formData.description }}
            </div> -->
            
                
            <div class="preview-content h-[70vh] overflow-y-auto">
                <div v-if="editorMode === 'markdown'">
                    <MdEditorPreview v-model="formData.content" />
                </div>
                <div v-else class="prose" v-html="formData.content"></div>
            </div>
        </el-dialog>

        <!-- 分类选择弹窗 -->
        <CategoryDialog ref="categoryDialogRef" @confirm="onConfirmPublish" @close="onCancelPublish" />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import MdEditor from '@/components/Markdown/index.vue'
import MdEditorPreview from '@/components/Markdown/preview.vue'
import Editor from '@/components/Editor/index.vue'
import { message } from '@/utils/message'
import { messageBox } from '@/utils/messageBox'
import xss from 'xss'
import TagDropdown from './TagDropdown.vue'
import CategoryDialog from './CategoryDialog.vue'
import { Close, Plus } from '@element-plus/icons-vue'
import { ElInput, ElButton, ElIcon, ElUpload } from 'element-plus'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const router = useRouter()
const route = useRoute()

// 分类弹窗引用
const categoryDialogRef = ref<any>(null)

// 标签下拉状态
const showTagDropdown = ref(false)

// 文件上传引用
const fileInputRef = ref<HTMLInputElement | null>(null)
const imageInputRef = ref<HTMLInputElement | null>(null)

// 定义表单数据类型
interface FormData {
    title: string
    content: string
    description: string
    tags: string[]
    coverImage?: string
    attachments?: Array<{
        name: string
        file?: File
    }>
}

// 组件逻辑
const formData = ref<FormData>({
    title: '',
    content: '',
    description: '',
    tags: [],
    attachments: []
})

// 页面状态
const isSubmitting = ref(false)
const showPreview = ref(false)
const editorMode = ref<'markdown' | 'editor'>('markdown')

// 计算属性
const contentLength = computed(() => {
    // 移除HTML标签后计算字数
    const textContent = formData.value.content.replace(/<[^>]*>/g, '')
    return textContent.length
})

// 监听内容变化
watch(() => formData.value.content, (newContent) => {
    console.log('内容更新:', newContent)
}, { immediate: true, deep: true })

// 从URL参数获取表情
onMounted(() => {
    const emoji = route.query.emoji as string
    
    if (emoji) {
        // 如果有表情参数，将其添加到内容中
        formData.value.content += emoji
    }
})

// 切换编辑器模式
const toggleEditorMode = async () => {
    const confirmed = await messageBox.confirm('切换编辑器模式将不会保存当前内容，是否继续？')
    if (confirmed) {
        editorMode.value = editorMode.value === 'markdown' ? 'editor' : 'markdown'
        formData.value.content = ''
    }
}

// 切换预览
const togglePreview = () => {
    if(formData.value.title === ''){
        message.warning('请先输入标题')
        return
    }
    if(formData.value.content === ''){
        message.warning('请先输入内容')
        return
    }
    showPreview.value = !showPreview.value
}

const tagInput = ref('')
const showTagInput = ref(false)

// 显示标签输入框
const showTagInputField = () => {
    if (formData.value.tags.length < 3) {
        showTagInput.value = true
    } else {
        message.warning('最多只能添加三个标签')
    }
}

// 添加标签
const handleAddTag = () => {
    const tag = tagInput.value.trim()
    if (tag) {
        if (formData.value.tags.length >= 3) {
            message.warning('最多只能添加三个标签')
            return
        }
        if (formData.value.tags.includes(tag)) {
            message.warning('该标签已存在')
            return
        }
        formData.value.tags.push(tag)
        tagInput.value = ''
        showTagInput.value = false
    }
}

// 删除标签
const handleRemoveTag = (index: number) => {
    formData.value.tags.splice(index, 1)
}

// 表单验证
const validateForm = (): string | null => {
    if (!formData.value.title.trim()) {
        return '请输入标题'
    }

    if (formData.value.title.trim().length < 5) {
        return '标题至少需要5个字符'
    }

    if (formData.value.title.trim().length > 100) {
        return '标题不能超过100个字符'
    }

    if (!formData.value.content.trim()) {
        return '请输入内容'
    }

    if (contentLength.value < 10) {
        return '内容至少需要10个字符'
    }

    return null
}

// 处理发布确认
const handleSubmit = async () => {
    try {
        // 表单验证
        const validationError = validateForm()
        if (validationError) {
            await messageBox.alert(validationError)
            return
        }

        isSubmitting.value = true

        // XSS 过滤
        const safeContent = xss(formData.value.content)
        
        // 准备提交数据
        const postData = {
            title: formData.value.title.trim(),
            content: safeContent,
            description: formData.value.description,
            tags: formData.value.tags,
            coverImage: formData.value.coverImage,
            attachments: formData.value.attachments,
            createTime: new Date().toISOString()
        }

        console.log('准备提交数据:', postData)
        
        // 打开分类选择弹窗
        if (categoryDialogRef.value) {
            categoryDialogRef.value.openDialog(postData)
        }
    } catch (error) {
        console.error('发布失败:', error)
        isSubmitting.value = false
        await messageBox.alert('发布失败，请重试', { type: 'error' })
    }
}

// 确认发布（选择分类后）
const onConfirmPublish = (finalPostData: any) => {
    console.log('最终发布数据:', finalPostData)
    
    // TODO: 调用发布API
    // 这里模拟API调用
    setTimeout(() => {
        message.success('发布成功')
        isSubmitting.value = false
        // 跳转到论坛首页
        router.push('/forum')
    }, 1000)
}

// 取消发布
const onCancelPublish = () => {
    console.log('用户取消了发布')
    isSubmitting.value = false
}

// 处理封面图片上传
const handleCoverUpload = (file: any) => {
    if (!file) return
    
    // 检查文件类型
    const isImage = /^image\//.test(file.type)
    if (!isImage) {
        message.error('请上传图片文件')
        return
    }
    
    // 检查文件大小
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
        message.error('图片大小不能超过2MB')
        return
    }
    
    // 转为base64显示
    const reader = new FileReader()
    reader.readAsDataURL(file.raw || file)
    reader.onload = () => {
        formData.value.coverImage = reader.result as string
    }
    
    return false // 阻止自动上传
}

// 移除封面图片
const removeCoverImage = () => {
    formData.value.coverImage = undefined
}

// 处理附件上传
const handleAttachmentUpload = (file: any) => {
    if (!file) return
    
    // 检查文件大小
    const isLt20M = file.size / 1024 / 1024 < 20
    if (!isLt20M) {
        message.error('文件大小不能超过20MB')
        return
    }
    
    // 添加到附件列表
    formData.value.attachments?.push({
        name: file.name,
        file: file.raw || file
    })
    
    return false // 阻止自动上传
}

// 移除附件
const removeAttachment = (index: number) => {
    formData.value.attachments?.splice(index, 1)
}

// 处理标签点击
const handleTopicClick = () => {
    showTagDropdown.value = !showTagDropdown.value
}

// 处理标签选择
const onTagSelected = (tag: string) => {
    if (formData.value.tags.length >= 3) {
        message.warning('最多只能添加三个标签')
        return
    }
    
    if (formData.value.tags.includes(tag)) {
        message.warning('该标签已存在')
        return
    }
    
    formData.value.tags.push(tag)
}

// 页面离开前确认
window.addEventListener('beforeunload', (e) => {
    if (formData.value.title.trim() || formData.value.content.trim()) {
        e.preventDefault()
        e.returnValue = '确定要离开吗？未保存的内容将会丢失。'
    }
})
</script>

<style scoped>
/* 添加一些过渡效果 */
.transition-colors {
    transition: background-color 0.2s ease, color 0.2s ease;
}

/* 预览内容样式 */
.preview-dialog {
    :deep(.el-dialog__body) {
        padding: 20px;
    }
}

.preview-content {
    max-height: 70vh;
    overflow-y: auto;
}

.prose {
    max-width: none;
}

.prose h1 {
    @apply text-2xl font-bold mb-4;
}

.prose h2 {
    @apply text-xl font-bold mb-3;
}

.prose h3 {
    @apply text-lg font-bold mb-2;
}

.prose p {
    @apply mb-3;
}

.prose ul, .prose ol {
    @apply pl-6 mb-3;
}

.prose blockquote {
    @apply border-l-4 border-gray-300 pl-4 italic;
}

.prose img {
    @apply max-w-full h-auto rounded-lg;
}

.prose a {
    @apply text-blue-600 hover:text-blue-800;
}

/* 自定义输入框样式 */
input:focus {
    outline: none;
}



:deep(.el-textarea__inner) {
    box-shadow: none !important;
    border-radius: 0;
    border: none;
    border-bottom: 1px solid #e2e8f0;
    padding-left: 0;
    padding-right: 0;
}

:deep(.el-textarea__inner:focus) {
    border-bottom: 2px solid #3b82f6;
}
</style>
